const App = {
    data() {
        return {
            loading:false,
            dataForm: { Attachment_URL: '' },
            childDataForm: [{}],
            childDataForm1: [{}],
            action: '',
            nodeKey: '',
            crop: [],
            subsidy_policy_type: [],
            relativePath: '',
            fileUrl:'',
            showDialog:false
        };
    },
    mounted() {
        //初始化
        let ls_URL = window.location.href;
        this.nodeKey = getQueryObject(ls_URL, "nodeKey");// 获取 nodeKey 参数
        this.action = getQueryObject(ls_URL, "action");   // 获取 action 参数
        this.relativePath = ls_URL.substring(
            ls_URL.lastIndexOf("view"),
            ls_URL.length
        );
        if (this.action === 'Modify') {
            this.getData(this.nodeKey);
        }
        //
        this.getcrop();
    },
    methods: {
        validator(rule, value, callback) {
            let Subsidy_Amount = "0";
            this.childDataForm.filter(i=>i.Row_Status != '1').forEach(item=>{
                if (!isNaN(item.Subsidy_Amount)) {
                    Subsidy_Amount = accAdd(Subsidy_Amount,item.Subsidy_Amount)
                }
            })
            if (!value) {
                callback(new Error('请输入补贴金额'));
            } else if (Subsidy_Amount > this.dataForm.Subsidy_Amount) {
                callback(new Error('请输入补贴金额不能大于' + this.dataForm.Subsidy_Amount));
            } else {
                callback();
            }
        },
        validator1(rule, value, callback){
            if (!value) {
                callback(new Error('请输入补贴金额'));
            } else if (isNaN(value)) {
                callback(new Error('请输入正确的补贴金额'));
            } else {
                callback();
            }
        },
        getcrop() {
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                method: "post",
                data: {
                    Data: 'crop',
                    Condition: `Row_Status='0'`,
                },
                success: (res) => {
                    this.crop = res;
                }, complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                method: "post",
                data: {
                    Data: 'subsidy_policy_type',
                    Condition: `Row_Status='0'`,
                },
                success: (res) => {
                    this.subsidy_policy_type = res;
                }, complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
            });
        },
        getData(nodeKey) {//查询
            const that = this;
            //获取对应子表表单对象
            let lJSONObject_Children = new Array();
            let lJSONObject_ChildData = new Object();
            try {
                //可能涉及多个子表
                document.getElementById("ChildTable").querySelectorAll(".el-descriptions").forEach(item => {
                    let lJSONObject_ChildData_Options = new Object();
                    lJSONObject_ChildData_Options = JSON.parse(item.getAttribute("data-options"));

                    let ls_ChildTableName = lJSONObject_ChildData_Options.TableName;
                    let ls_ChildDataForm = lJSONObject_ChildData_Options.form;

                    lJSONObject_ChildData[ls_ChildTableName] = ls_ChildDataForm;
                    lJSONObject_Children[ls_ChildTableName] = 'ChildTable';
                })
            } catch (error) { }
            //获得对应表单对象
            let lJSONObject_Data_Options = new Object();
            lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));
            let ls_DataForm = lJSONObject_Data_Options.form;
            let ls_TableName = lJSONObject_Data_Options.TableName;
            let ls_primary_key = lJSONObject_Data_Options.primary_key

            let lJSONObject_Data = new Object();
            lJSONObject_Data[ls_TableName] = ls_DataForm;
            lJSONObject_Data = { ...lJSONObject_Data, ...lJSONObject_ChildData };

            let lJSONObject_TableName = new Object();
            lJSONObject_TableName[ls_TableName] = 'MainTable'
            lJSONObject_TableName = { ...lJSONObject_TableName, ...lJSONObject_ChildData };
            for (let key in lJSONObject_TableName) {
                $.ajax({
                    headers: requestHeaders(),
                    url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                    method: "post",
                    data: {
                        Data: key,
                        Condition: `${ls_primary_key}='${nodeKey}'`,
                    },
                    success: (res) => {
                        if (lJSONObject_TableName[key] == 'MainTable') {
                            that[lJSONObject_Data[key]] = res[0];
                        } else {
                            that[lJSONObject_Data[key]] = res;
                        }
                    }, complete: (XMLHttpRequest) => {
                        requestPretreatment(XMLHttpRequest);
                    },
                });
            }
        },
        //提交表单
        handleSubmit() {
            let ls_URL = window.location.href;
            const action = getQueryObject(ls_URL, "action");   // 获取 action 参数
            let lJSONObject_Data_Options = new Object();
            lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));

            let ls_MainTableName = lJSONObject_Data_Options.TableName;
            let ls_DataForm = lJSONObject_Data_Options.form;
            //没有子表下面内容就会报错，try/catch抛出异常
            try {
                //可能涉及多个子表
                document.getElementById("ChildTable").querySelectorAll(".el-descriptions").forEach(item => {
                    let lJSONObject_ChildData_Options = new Object();
                    lJSONObject_ChildData_Options = JSON.parse(item.getAttribute("data-options"));

                    let ls_ChildTableName = lJSONObject_ChildData_Options.TableName;
                    let ls_ChildDataForm = lJSONObject_ChildData_Options.form;
                    let ls_ParentTableName = lJSONObject_ChildData_Options.ParentTableName;
                    //建立子表结构体
                    let JSONArray_ChildRecord = new Array();
                    JSONArray_ChildRecord = this[ls_ChildDataForm];
                    let JSONObject_ChildTable = new Object();
                    JSONObject_ChildTable[ls_ChildTableName] = JSONArray_ChildRecord;

                    this[ls_DataForm].Children = JSONObject_ChildTable;
                })
            } catch (error) {

            }
            //建立新增提交结构
            let lJSONObject_DataSet = new Object();
            if (action == 'Add') {
                let lJSONArray_Record = new Array();
                lJSONArray_Record.push(this[ls_DataForm]);
                let lJSONObject_Table = new Object();
                lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;
                lJSONObject_DataSet[action] = lJSONObject_Table;
            } else if (action == 'Modify') {
                const { add, modify } = this.deal(this[ls_DataForm]);
                let lJSONArray_Record = new Array();
                lJSONArray_Record.push(modify);

                let lJSONObject_Table = new Object();
                lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;

                lJSONObject_DataSet[action] = lJSONObject_Table;
                if (add != null) {
                    let lJSONArray_Record_Add = new Array();
                    lJSONArray_Record_Add.push(add);

                    let lJSONObject_Table_Add = new Object();
                    lJSONObject_Table_Add[ls_MainTableName] = lJSONArray_Record_Add;

                    lJSONObject_DataSet['Add'] = lJSONObject_Table_Add;
                }
            }
            let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
            if (!lJSONObject_DataSet['Add']) {
                lJSONObject_DataSet['Add'] = new Object();
            }
            lJSONObject_DataSet['Add']['base_operation_log'] = [{
                Operation_Type: '0',
                Operation_Path: this.relativePath,
                Operation_Main,
                Operation_Interface: "generalSave",
                Operation_IP: getIpAddress()
            }]
            submitSave(lJSONObject_DataSet, (res) => {
                if (res.Status == 'success') {
                    window.history.go(-1);
                }
            })
            // $.ajax({
            //     headers: requestHeaders(),
            //     url: `${mh}/generalBusiness/generalSave`,
            //     method: "post",
            //     data: {
            //         Data: JSON.stringify(lJSONObject_DataSet),
            //     },
            //     success: (res) => {
            //         if (res.Status == 'success') {
            //             window.history.go(-1);
            //         }
            //     }, complete: (XMLHttpRequest) => {
            //         requestPretreatment(XMLHttpRequest);
            //     },
            // });
        },
        deal(form) {    //将待提交的数据中添加和修改分离出来
            const add = deepClone(form), modify = deepClone(form);
            try {
                for (let key in form.Children) {
                    let add_Data = [], modify_Data = [];
                    for (const i in modify.Children[key]) {
                        const obj = modify.Children[key][i];
                        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                            add_Data.push(obj);
                        } else {
                            modify_Data.push(obj);
                        }
                    }
                    add.Children[key] = add_Data;
                    modify.Children[key] = modify_Data;
                }
                let lb_is = true;
                for (let key in add.Children) {
                    if (add.Children[key].length > 0) {
                        lb_is = false;
                    }
                }
                if (lb_is) {
                    return { add: null, modify };
                }
                return { add, modify };
            } catch (error) {
                return { add: null, modify };
            }
        },
        handleAdd(formName) {
            if (this.action === 'Add') {
                this[formName].push({})
            } else if (this.action === 'Modify') {
                let lJSONObject_Data_Options = new Object();
                lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));
                let ls_primary_key = lJSONObject_Data_Options.primary_key;
                let lJSONObject_Data = new Object();
                lJSONObject_Data[ls_primary_key] = this.nodeKey;
                this[formName].push(lJSONObject_Data);
            }
        },
        preview(row) {
            this.fileUrl = photo + row.Attachment_URL;
            this.showDialog = true;
        },
        async download(row) {
            // if (row.Attachment_URL) {
            //     window.location.href = photo + row.Attachment_URL;
            // }
            let apiUrl = photo + row.Attachment_URL;
            let fileName = apiUrl.split('/').pop();
            try {
                const response = await fetch(apiUrl);
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);

                const a = document.createElement('a');
                a.href = url;
                a.download = fileName || 'download';
                document.body.appendChild(a);
                a.click();

                // 清理
                setTimeout(() => {
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                }, 100);
            } catch (error) {
                console.error('下载失败:', error);
            }
        },
        handleRemove(formName) {
            if (this.action === 'Add') {
                if (this[formName].length > 1) {
                    this[formName].pop();
                } else {
                    this.$message({
                        message: '不能在删除了',
                        type: 'warning'
                    })
                }
            } else if (this.action === 'Modify') {
                if (this[formName].filter(item => item.Row_Status != '1').length > 1) {
                    let i = this[formName].filter(item => item.Row_Status != '1').length - 1
                    let obj = this[formName].filter(item => item.Row_Status != '1')[i]
                    if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                        this[formName].pop();
                    } else {
                        this.$confirm('该操作将删除此条数据,是否继续?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning',
                        }).then(() => {
                            this[formName].filter(item => item.Row_Status != '1')[i].Row_Status = '1'
                        }).catch(() => {
                            this.$message({
                                type: 'warning',
                                message: '已取消删除'
                            });
                        });
                    }
                } else {
                    this.$message({
                        message: '不能在删除了',
                        type: 'warning'
                    })
                }
            }
        },
        goBack() {
            window.history.back();
        },
    },
};
const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}
app.component('yl-upload', ylUpload);
app.component('yl-online-preview', ylOnlinePreview);
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");
